package com.dubito.lucene.query;

import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.DirectoryReader;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.*;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.wltea.analyzer.lucene.IKAnalyzer;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

/**
 * @author liliang
 * @description:
 * @date 2018/4/28.
 */
public class Query子类 {

    public static void main(String[] args) throws IOException {
        Directory directory = FSDirectory.open(new File("/Users/liliang/Downloads/index_db"));
        IndexReader indexReader = DirectoryReader.open(directory);
        IndexSearcher indexSearcher = new IndexSearcher(indexReader);

        // 创建 query 关键字查询
        Query query1 = new TermQuery(new Term("fileContent", "明"));
        // 前缀查询
        Query query2 = new PrefixQuery(new Term("fileContent", "黄"));
        // 模糊查询
        Query query3 = new FuzzyQuery(new Term("fileContent", "明"));
        // 正则表达式查询
        Query query4 = new RegexpQuery(new Term("fileContent", "明|乡"));
        // 通配符
        Query query5 = new WildcardQuery(new Term("fileContent", "黄*"));
        // Boolean 查询
        BooleanQuery bool = new BooleanQuery();
        // 必须有
        bool.add(query1, BooleanClause.Occur.MUST);
        // 必须没有
        bool.add(query2, BooleanClause.Occur.MUST_NOT);

        // 短语查询
        String keyWork = "床前明月光，疑是地上霜";
        PhraseQuery phraseQuery = new PhraseQuery();
        IKAnalyzer analyzer = new IKAnalyzer();
        TokenStream tokenStream = analyzer.tokenStream("fileContent", new StringReader(keyWork));
        while (tokenStream.incrementToken()) {
            CharTermAttribute attribute = tokenStream.getAttribute(CharTermAttribute.class);
            phraseQuery.add(new Term("fileContent",attribute.toString()));
        }
        analyzer.close();

        TopDocs topDocs = indexSearcher.search(phraseQuery, 4);
        System.out.println("总命中记录数:" + topDocs.totalHits);
        // 分数文档
        ScoreDoc[] scoreDocs = topDocs.scoreDocs;
        for (ScoreDoc scoreDoc : scoreDocs) {
            int docId = scoreDoc.doc;
            System.out.println("文档 id" + docId);
            Document document = indexSearcher.doc(docId);
            System.out.println("id:" + document.get("id"));
            System.out.println("name :" + document.get("name"));
            System.out.println("path :" + document.get("path"));
            System.out.println("content :" + document.get("fileContent"));
        }
        indexReader.close();
    }

}
